//
//  WmcHomeVC+Function.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/5/12.
//

import Foundation
import YPGraphicEngine
import YPNetwork

public extension WmcHomeVC {
    /// 视频录制状态
    enum VideoRecordState {
        /// 停止
        case stop
        /// 进行中
        case being
        /// 暂停
        case pause
    }
    /// 边拍边拼状态
    enum PhotoCombineState {
        /// 进行中
        case being
        /// 停止
        case stop
    }
}

extension WmcHomeVC {
    // MARK: - 交互逻辑

    /// 点击本地相册
    func clickLocalAlbumBtn() {
        // 权限判断
        let photoAlbumStatus = WmcAuthorizedManager.photoAlbum()
        if photoAlbumStatus.info.isAvailable {
            WmcLocalMediaAlbumDBManager.searchMediaData(page: 1, pageSize: 20) { [weak self] list in
                guard let weakSelf = self else { return }
                // 进行筛选操作
                var newList: [WmcLocalMediaAlbumDBManager.DBModel] = []
                let defaultMediaTypes: [WmcMedia.MediaType] = [
                    .image, .video,
                ]
                if let mediaTypes = weakSelf.homeDelegate?.localAlbumLoadMediaType(.current,
                                                                                   defaultMediaTypes: defaultMediaTypes)
                {
                    for meida in list {
                        if mediaTypes.contains(meida.mediaType) {
                            newList.append(meida)
                        }
                    }
                } else {
                    newList = list
                }

                // 如果图片空，则返回
                guard newList.count > 0 else {
                    WmcHudManager.toast("暂无图片")
                    return
                }
                // 需要关相机
                weakSelf.stopCamera()

                let browseVM = WmcMediaBrowseVM()
                browseVM.albumType = .local
                browseVM.topRightStyle = .allPhoto
                browseVM.topLeftStyle = .backTitle(title: "本地相册")
                browseVM.mediaList = weakSelf.viewModel.localMediaAlbumPhotoListRelay.value.asWmcMediaList
                browseVM.dataSourceList = weakSelf.viewModel.localMediaAlbumPhotoListRelay.value
                browseVM.currentMediaWatermarkBlock = { idx in
                    let dbModel = weakSelf.viewModel.localMediaAlbumPhotoListRelay.value[idx]
                    let wmJson = dbModel.mediaInfoType.watermarkJson
                    let wmc = WmcWatermarkDetailModel.deserialize(from: wmJson)
                    return wmc
                }
                // 事件回调
                browseVM.actionBlock = { [weak self] type, index, vm in
                    guard let weakSelf = self else { return }
                    let imageList = weakSelf.viewModel.localMediaAlbumPhotoListRelay.value
                    guard let dbImage = imageList.yp.object(at: index) else { return }
                    switch type {
                    case .delete:
                        vm.presentDeleteAlert { [weak self] in
                            WmcLocalMediaAlbumDBManager.deleteMedia(id: dbImage.id) { [weak self] result in
                                guard let weakSelf = self else { return }
                                if result {
                                    weakSelf.viewModel.syncLocalAlbumList()
                                    vm.remove(at: index)
                                    WmcHudManager.toast("删除成功")
                                }
                            }
                        }
                    case .upload:
                        let syncAlertView: () -> Void = {
                            let syncSettingsView = WmcSyncSettingsView.showInView(style: .confirmType, isMustSelected: true)
                            syncSettingsView.ensureClosure = { [weak self] list in
                                guard let weakSelf = self else { return }
                                // 继续上传
                                WmcLogManager.Log("继续上传")
                                weakSelf.uploadTask(dbImage: dbImage, index: index)
                            }
                            weakSelf.addSubview(syncSettingsView)
                            
                            let presentVC = WmcPresentVC(config: .init(style: .sheet(), contentView: syncSettingsView, contentLayoutBlock: { make in
                                make.left.right.bottom.equalToSuperview()
                                make.height.equalTo(373)
                            }))
                            presentVC.show()
                        }
                        
                        if !WmcLoginManager.shared.isLogin {
                            weakSelf.showLoginMoreRightsAlert {
                                YPWmcManager.shared.delegate.loginDelegate?.loginNeed(.current, animated: true, success: {
                                    syncAlertView()
                                }, failure: {
                                    WmcHudManager.toast("登录失败")
                                })
                            }
                        } else {
                            syncAlertView()
                        }

                    default: break
                    }
                }
                WmcNavigatorManager.push(.imageBrowse, style: .bottom, parms: browseVM)
            }
        } else {
            WmcAuthorizedManager.handleAlbumAuthorizationNotAvailable()
        }
    }

    /// 创建上传任务
    func uploadTask(dbImage: WmcLocalMediaAlbumDBManager.DBModel, index: Int) {
        WmcHudManager.toast("已上传")

        if let filePath = dbImage.mediaInfoType.relativePath,
           let watermarkJson = dbImage.mediaInfoType.watermarkJson,
           let jsonData: Data = watermarkJson.data(using: .utf8),
           let watermarkInfoDic = try? JSONSerialization.jsonObject(with: jsonData, options: .fragmentsAllowed) as? [String: Any],
           let media: WmcMedia = viewModel.localMediaAlbumPhotoListRelay.value.asWmcMediaList.yp.object(at: index)
        {
            let wmId = watermarkInfoDic["wmId"] as? Int
            let takeTimeDic: [String: Any] = watermarkInfoDic["time"] as? [String: Any] ?? [:]
            let takeTimestamp = takeTimeDic["time"] as? Double
            let isNetTime = takeTimeDic["isNetTime"] as? Bool
            var takeTimeDate = Date()

            if var takeTimestamp = takeTimestamp, isNetTime == true {
                takeTimestamp = takeTimestamp - 8 * 60 * 60
                takeTimeDate = Date(timeIntervalSince1970: takeTimestamp)
            }

            let uploadParams = WmcMediaUploadResourceParameterModel()
            if media is WmcImage { // 图片
                uploadParams.type = 0
                uploadParams.format = "png"
            } else if media is WmcVideo { // 视频
                uploadParams.type = 1
                uploadParams.format = "mp4"
                if let path = dbImage.mediaInfoType.filePath {
                    let videoTime = Int(AVAsset(url: path.yp.fileUrl).duration.seconds)
                    uploadParams.videoTime = videoTime
                }
            }
            uploadParams.appId = 101 // 锁死水印相机appid
            uploadParams.entryId = 1
            uploadParams.wmcInfo = watermarkInfoDic
            if let uid = WmcLoginManager.shared.yupaoAccountModel?.userId {
                uploadParams.uid = Int(uid)
            }
            uploadParams.wmId = wmId
            uploadParams.takeTime = takeTimeDate.yp.string(.ymd_hms_iso8601, identifier: .asia(.Shanghai))
            uploadParams.previewImagePath = dbImage.previewImagerelativePath
            WmcUploadQueueManager.appendUploadTask(path: filePath, model: uploadParams)
        }
    }

    // MARK: - 隐式逻辑

    /// 适配布局
    func autoFrame() {
        let cameraBounds = cameraBackgroundView.frame
        watermarkContentView.frame = cameraBounds
        controlView.frame = cameraBounds
        let headerViewFrame = headerView.frame
        var height = cameraBounds.height
        if !headerView.isTransparent { // 透明
            height -= headerViewFrame.height
        }
        noticeView.frame = CGRect(x: 0,
                                  y: headerViewFrame.height,
                                  width: cameraBounds.width,
                                  height: height)
    }

    /// 设置重力感应
    func deviceMotionGravitySensor() {
        // 进行监听
        WmcMotionManager.shared.orientation.subscribe(onNext: { [weak self] orientation in
            guard let weakSelf = self else { return }
            // 震动反馈
            if weakSelf.isAccelerometerFeedback {
                YPDevice.PlayShake(.light)
            }
            // 布局转向
            weakSelf.setControlOrientation(orientation)
        }).disposed(by: rx.disposeBag)
    }

    /// 根据重感设置按钮匹配方向
    func setControlOrientation(_ orientation: UIDeviceOrientation) {
        // 询问外部代理支持的方向
        var defaultOrientation: [UIDeviceOrientation] = viewModel.defaultOrientation
        if let _defaultOrientation = homeDelegate?.cameraRotatingOrientation(.current,
                                                                             functionMode: viewModel.functionMode,
                                                                             videoRecordState: viewModel.videoRecordState,
                                                                             defaultOrientation: defaultOrientation)
        {
            defaultOrientation = _defaultOrientation
        }

        guard defaultOrientation.contains(orientation) else { return }

        var angle = 0
        switch orientation {
        case .portrait: // 正常
            angle = 0
        case .landscapeLeft: // 左
            angle = 90
        case .landscapeRight: // 右
            angle = -90
        case .portraitUpsideDown: // 反向
            angle = 180
        default: break
        }

        let transform = CGAffineTransform(rotationAngle: CGFloat(angle).yp.angleToRadian)

        // 水印转向
        watermarkContentView.transform = transform
        // 通知位
        noticeView.transform = transform
        // 控制器
        controlView.transform = transform
        // 二维码
        if viewModel.hasShowQRGuide { // 如果已经显示过用户引导了,二维码跟着屏幕旋转
            staticQRView.transform = transform
            updateStaticQRCodeViewFrame(with: orientation)
        }
        // 各种按钮的动画
//        let buttoms: [UIView] = [
//            headerView.menuBtn,
//            headerView.flashBtn,
//
//            headerMenuView.aspectRatioBtn,
//            headerMenuView.contactBtn,
//            headerMenuView.delayBtn,
//            headerMenuView.cameraSettingBtn,
//
//            footerView.localAlbumBtn,
//            footerView.watermarkBtn,
//            footerView.flipBtn,
//            footerView.cloudAlbumBtn,
//
//            positioningBtn,
//        ]
//        buttoms.forEach { view in
//            Wmc_SpringAnimation() {
//                view.transform = transform
//            }
//        }

        autoFrame()
        // 转向用透明度动画
        watermarkContentView.alpha = 0
        controlView.alpha = 0
        UIView.animate(withDuration: Wmc_animationDuration) { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.watermarkContentView.alpha = 1
            weakSelf.controlView.alpha = 1
        }
        // 水印虚线框闪烁
        YPGCD.Delay(delay: 0.5) { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.controlView.flashDottedLayer()
        }
    }

    /// 左下角预览按钮的图片替换
    func setPreViewImage() {
        // 相册权限判断
        let photoAlbumStatus = WmcAuthorizedManager.photoAlbum()
        if photoAlbumStatus.info.isAvailable, // 有权
           let previewImagePath = viewModel.localMediaAlbumPhotoListRelay.value.first?.previewImagePath,
           let previewImage = UIImage(contentsOfFile: previewImagePath)
        {
            footerView.localAlbumBtn.setImage(previewImage)
        } else {
            footerView.localAlbumBtn.setImage("home_tool_preview".wmc_image)
        }
    }

    /// 更新水印
    func updateWatermarkView() {
        watermarkContentView.updateWatermark()
    }

    /// 编辑水印
    func editWatermark(_ watermarkModel: WmcWatermarkDetailModel) {
        // 询问外部代理将如何对该事件进行处理
        var actionType: WmcActionType = .default
        if let _actionType = homeDelegate?.watermarkWillEdit(.current, watermarkModel: watermarkModel) {
            actionType = _actionType
        }
        // 默认处理
        actionType.transactionDefaultCase {
            let vm = WmcEditWatermarkVM()
            vm.watermarkStyleMode = .dynamicEdit
            vm.watermarkModel = watermarkModel
            WmcNavigatorManager.push(.editWatermark, parms: vm)
            // 当编辑完成后的回调
            vm.editCompleteBlock = { [weak self] wmModel in
                guard let weakSelf = self else { return }
                weakSelf.viewModel.setWatermarkModel(wmModel)
            }
        }
    }
    
    /// 根据手机设备方向更新二维码控件frame
    func updateStaticQRCodeViewFrame(with orientation: UIDeviceOrientation) {
        switch orientation {
        case .portrait: // 正常
            staticQRView.snp.remakeConstraints { make in
                make.top.equalTo(headerView.snp.bottom).offset(hMargin)
                make.right.equalTo(-hMargin)
            }
        case .portraitUpsideDown: // 颠倒
            staticQRView.snp.remakeConstraints { make in
                make.left.equalTo(hMargin)
                make.bottom.equalTo(footerView.snp.top).offset(-hMargin)
            }
        case .landscapeLeft: // 向左横屏
            staticQRView.snp.remakeConstraints { make in
                make.right.equalTo(-hMargin)
                make.bottom.equalTo(footerView.snp.top).offset(-hMargin)
            }
        case .landscapeRight: // 向右横屏
            staticQRView.snp.remakeConstraints { make in
                make.left.equalTo(hMargin)
                make.top.equalTo(headerView.snp.bottom).offset(hMargin)
            }
        default: break
        }
        staticQRView.snp.makeConstraints { make in
            make.width.equalTo(qrcodeW)
            make.height.equalTo(qrcodeH)
        }
    }

    
    /// 切换中部UI模式
    func switchMode(_ functionMode: WmcButtonItemType.HomeFunctionMode) {
        watermarkContentView.isHidden = true
        controlView.isIgnoreWatermarkFrames = false // 增加水印透传
        controlView.aiLogoView.isHidden = true
        controlView.dottedLayer.strokeColor = UIColor.white.cgColor
        // 旋转方向控制
        isAccelerometerFeedback = true
        viewModel.defaultOrientation = [
            .unknown, .portrait, .portraitUpsideDown, .landscapeLeft, .landscapeRight, .faceUp, .faceDown,
        ]
        switch functionMode {
        case .edit: break
        case .rebarCount:
            controlView.isIgnoreWatermarkFrames = true // 移除水印透传
            controlView.aiLogoView.isHidden = false
            controlView.dottedLayer.strokeColor = UIColor.clear.cgColor
            // 仅支持正向
            isAccelerometerFeedback = false
            viewModel.defaultOrientation = [.portrait]
        case .photo, .photoAndCombine:
            watermarkContentView.isHidden = false
        case .video:
            watermarkContentView.isHidden = false
        case .custom: break
        }
    }

    // MARK: - 相机方法

    /// 添加相机
    func addCameraView() {
        print("添加相机")
        cameraView = YPGECameraView()
        guard let cameraView = cameraView else { return }
        cameraBackgroundView.addSubview(cameraView)
        cameraView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        // 开启相机
        startCamera()
        // 监听相机摄像头切换
        listenCameraRotate()
        // 添加滤镜
        addFilter()
        // 设置初始画幅
        setInitialAspectRatio()
        // 设置初始分辨率
        setInitialResolution()
        // 初始化闪光灯
//        setInitialFlashMode()
        controlView.setCameraView(cameraView)
        headerView.refreshFlashBtnState(cameraView)
    }

    /// 点击翻转
    func clickFlip() {
        rotateCamera()
        // 恢复闪光灯模式
        restoreFlashMode()
//        if let cameraView = cameraView {
//            headerView.refreshFlashBtnState(cameraView)
//        }
        // 重置焦距倍数显示
        focusAdjustView.set(scale: 1.0, isShowScales: false)
    }

    /// 翻转相机
    func rotateCamera() {
        YPDevice.PlayShake(.medium)
        // 先停止捕捉画面,再修改分辨率,防止画面闪烁
//        cameraView?.stopCapture()
        // 切换摄像头
        cameraView?.rotateCamera()
        // 恢复捕捉画面
//        cameraView?.startCapture()
        cameraView?.setExposure(0)
    }
    
    
    /// 恢复闪光灯模式
    func restoreFlashMode() {
        if cameraView?.position() != .back {
            return
        }
        var flashMode: YPGECamera.FlashMode?
        switch viewModel.functionMode {
        case .photo, .photoAndCombine:
            let name = WmcButtonItemType.HomeFunctionMode.photo.name
            flashMode = viewModel.flashModes[name] ?? .off
        case .video, .rebarCount:
            let name = viewModel.functionMode.name
            flashMode = viewModel.flashModes[name] ?? .off
        default:
            break
        }
        if let flashMode = flashMode {
            setFlashMode(flashMode, cacheState: false)
        }
    }

    /// 设置闪光灯
    func setFlashMode(_ flashMode: YPGECamera.FlashMode, cacheState: Bool = true) {
        headerView.flashBtn.flashMode = flashMode
        cameraView?.setFlashMode(flashMode)
        if cacheState {
            switch self.viewModel.functionMode {
            case .photo, .photoAndCombine:
                let name = WmcButtonItemType.HomeFunctionMode.photo.name
                viewModel.flashModes[name] = flashMode
            case .rebarCount, .video:
                let name = viewModel.functionMode.name
                viewModel.flashModes[name] = flashMode
            default:
                break
            }
        }
    }
    
    /// 关闭手电筒（开启手电筒时跳转到别的页面需要关掉手电筒）
    /// - Parameter cacheState: 是否缓存闪光灯状态
    func turnOffElectricTorch(cacheState: Bool) {
        if headerView.flashBtn.flashMode == .torch {
            setFlashMode(.off, cacheState: cacheState)
        }
    }
    
    /// 恢复手电筒，如果之前是开启的，跳转到别的页面后，返回拍照页面需要恢复手电筒
    func restoreElectricTorch() {
        if cameraView?.position() == .back,
           let flashMode = viewModel.flashModes[viewModel.functionMode.name],
           flashMode == .torch {
            setFlashMode(.torch)
        }
    }

    /// 停止相机
    func stopCamera() {
        print("关闭相机")
        cameraView?.stopCapture()
        WmcLogManager.Log("关闭相机\(cameraView)")
        // TODO: 橙哥发现的GPUImage需要释放相关内存
//        PRGPUImageContext.sharedFramebufferCache()?.purgeAllUnassignedFramebuffers()
//        PRGPUImageContext.setActiveShaderProgram(nil)
    }

    /// 开启相机
    func startCamera() {
        // 判断权限开启，和权限弹窗有关0x000000013a811600
        print("开启相机")
        let cameraStatus = WmcAuthorizedManager.camera()
        if cameraStatus.info.isAvailable {
            cameraView?.startCapture()
            WmcLogManager.Log("开启相机\(cameraView)")
        } else {
            WmcLogManager.Log("开启相机失败，原因：无相机访问权限！status：\(cameraStatus)")
        }
    }

    func setLocationWaiting() {
        positioningBtn.label.textColor = .wmc_grayH2_323233
        positioningBtn.backgroundColor = .wmc_white_FFFFFF
        positioningBtn.label.text = "定位中"
        positioningBtn.imageView.image = "location_waiting".wmc_image
        positioningBtn.isEnabled = false
    }

    /// 设置定位成功状态
    func setLocationSuccess() {
        positioningBtn.label.textColor = .wmc_grayH2_323233
        positioningBtn.backgroundColor = .wmc_white_FFFFFF
        positioningBtn.label.text = "定位成功"
        positioningBtn.imageView.image = "location_success_icon".wmc_image

        addLocationBtnAnimate { [weak self] in
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) { [weak self] in
                guard let weakSelf = self else { return }
                weakSelf.resetLocationBtn()
            }
        }
        positioningBtn.isEnabled = true
    }

    /// 设置定位失败状态
    func setLocationFailure() {
        positioningBtn.label.textColor = .wmc_grayH2_323233
        positioningBtn.backgroundColor = .wmc_white_FFFFFF
        positioningBtn.label.text = "定位失败"
        positioningBtn.imageView.image = "location_failure_icon".wmc_image

        addLocationBtnAnimate { [weak self] in
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) { [weak self] in
                guard let weakSelf = self else { return }
                weakSelf.resetLocationBtn()
            }
        }
        positioningBtn.isEnabled = true
    }

    /// 重置定位默认状态
    func resetLocationBtn() {
        UIView.animate(withDuration: 0.75, delay: 0.0, options: .curveEaseOut) { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.positioningBtn.backgroundColor = UIColor.clear.withAlphaComponent(0.0)
        }
        positioningBtn.label.textColor = .wmc_white_FFFFFF
        positioningBtn.label.text = "重新定位"
        positioningBtn.imageView.image = "home_tool_location".wmc_image
    }

    /// 定位按钮缩放动画
    func addLocationBtnAnimate(completion: (() -> Void)? = nil) {
        UIView.animate(withDuration: 0.15, delay: 0.0, options: .curveEaseInOut) { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.positioningBtn.transform = CGAffineTransform(scaleX: 1.2, y: 1.2)
        } completion: { _ in
            UIView.animate(withDuration: 0.15, delay: 0.0, options: .curveEaseInOut) { [weak self] in
                guard let weakSelf = self else { return }
                weakSelf.positioningBtn.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
            } completion: { _ in
                UIView.animate(withDuration: 0.15, delay: 0.0, options: .curveEaseInOut) { [weak self] in
                    guard let weakSelf = self else { return }
                    weakSelf.positioningBtn.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
                } completion: { _ in
                    completion?()
                }
            }
        }
    }

    /// 显示录制50s提示
    func showVideoRecording50STips() {
        videoRecording50STipsLabel.isHidden = false
        videoRecording50STipsLabel.yp.delayLast(10, actionBlock: { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.videoRecording50STipsLabel.isHidden = true
        })
    }

    /// 更多权限弹窗
    func showLoginMoreRightsAlert(btnAction: (() -> Void)?) {
        var style: WmcHomeMoreRightsAlert.Style = .watermarkCameraNotLogin
        switch YPWmcManager.shared.platform {
        case .watermarkCamera:
            break
        case .fishBubble:
            style = .yuPaoFirstTakePhoto
        case .recordWork:
            break
        case .saas:
            break
        }
        let vc = WmcHomeMoreRightsAlert.alert(style: style, btnAction: btnAction)
        vc.show()
    }
    
    /// 设置拍照次数
    func setTakePhotoCount() {
        if var takePhotoCount: Int = WmcUserdefault.object(forKey: .Tips.Home.locationTipsView) {
            takePhotoCount += 1
            if takePhotoCount == 3 {
                locationGuideView.isHidden = false
            }
            WmcUserdefault.save(value: takePhotoCount, forKey: .Tips.Home.locationTipsView)
        } else {
            WmcUserdefault.save(value: 1, forKey: .Tips.Home.locationTipsView)
        }
    }
    
    /// 展示水印分享提示窗
    func showWatermarkShareAlert(_ model: WmcMediaWatermarkShareTemplate, dismissPresentVC: Bool) {
        let alert = WmcWatermarkShareAlertView()
        alert.configModel(model)
        alert.show()

        alert.useWatermarkBlock = { [weak self] wmModel in
            guard let weakSelf = self else { return }
            weakSelf.viewModel.setUserDataWatermarkModel(wmModel)
        }
        
        alert.didDismissBlock = { [weak self] in
            guard let weakSelf = self else { return }
            if dismissPresentVC {
                YPApp.CurrentVC?.dismiss(animated: true)
                weakSelf.controlView.isHidden = false
                weakSelf.watermarkContentView.isHidden = false
            }
        }
    }
    
    /// 展示邀请加入团队弹窗
    func showJoinTeamSheet(_ model: WmcMediaShareTeamModel, dismissPresentVC: Bool) {
        
        guard let remark = model.remark,let teamName = model.teamName else {
            return
        }
        ///先要判断用户是否已经登录
        WmcInviationAlertView.alert(note: remark, teamName: teamName, isLogin: WmcLoginManager.shared.isLogin) {[weak self] isLogin in
            if isLogin {
                guard let weakSelf = self else { return }
                weakSelf.gotoTeamAlbumHomePage(model: model)
            } else {
                YPWmcManager.shared.delegate.loginDelegate?.loginNeed(.current, animated: true, success: { [weak self] in
                    let currentVC = YPApp.CurrentVC
                    currentVC?.dismiss(animated: false, completion: {
                        //跳转团队首页
                        guard let weakSelf = self else { return }
                        weakSelf.gotoTeamAlbumHomePage(model: model)
                    })
                }, failure: {
                    let msg = "登录失败"
                    WmcHudManager.toast(msg)
                })
            }
        }.show()
    }
    
    /// 检查网络环境
    /// - Parameter type: 网络环境状态
    func checkNetworkStatus(type: YPNetworkReachabilityType) {
        if type == .notReachable {
            WmcTaskSchedulerManager.registerTask(key: .notNetworkLocationFailureTip) {
                return true
            } exceuteClosure: { [weak self] continueFunc in
                guard let weakSelf = self else { return }
                weakSelf.networkErrorTipView.isHidden = false
                weakSelf.networkErrorTipView.dismissClosure = {
                    continueFunc()
                }
            }
        } else {
            networkErrorTipView.dismiss()
            WmcTaskSchedulerManager.removeTask(key: .notNetworkLocationFailureTip)
        }
    }
    /// 更新相机分辨率
    func setCameraPreset(position: YPGECamera.Position? = nil) {
//        var preset: AVCaptureSession.Preset = .high
//        var _position: YPGECamera.Position = cameraView?.position() ?? .back
//        if let position = position {
//            _position = position
//        }
//        if case .photo = viewModel.functionMode,
//           _position == .back { // 如果是拍照,并且是后置摄像头
//            preset = viewModel.resolutionLevel.preset
//        }
//        cameraView?.setPreset(preset)
    }
    
    /// 重置相机焦距
    func resetCameraFocusScale() {
        let scale: CGFloat = 1.0
        controlView.setCameraZoomFactor(scale: scale, slient: true)
        focusAdjustView.set(scale: scale, isShowScales: false)
    }
}


extension WmcHomeVC {
    
    func gotoTeamAlbumHomePage(model: WmcMediaShareTeamModel) -> Void {
        self.viewModel.joinTeam(teamId: Int(model.teamId ?? "0") ?? 0) { teamAlbum in
            //跳转团队首页
            YPApp.CurrentVC?.dismiss(animated: true, completion: {[weak self] in
                guard let weakSelf = self else { return }
                let teamAlbumModel = WmcMediaTeamAlbumModel.init()
                teamAlbumModel.teamId = Int(model.teamId ?? "0") ?? 0
                teamAlbumModel.busId = model.teamId ?? "0"
                teamAlbumModel.albumId = teamAlbum.albumId
                teamAlbumModel.name = teamAlbum.name
                teamAlbumModel.teamOpenId = teamAlbum.teamOpenId
                /// 先把我的团队相册加入导航栏栈中
                let teamVC = WmvMyTeamVC()
                weakSelf.navigationController?.viewControllers.append(teamVC)
                weakSelf.stopCamera()
                WmcNavigatorManager.push(.teamCloudAlbum, parms: teamAlbumModel)
                WmcHudManager.toast("已成功加入团队")
            })
        }
    }
}
